<?php
/**
 * A simple description for this script
 *
 * PHP Version 5.2.0 or Upper version
 *
 * @package    Paylog
 * @author     Hidehito NOZAWA aka Suin <http://suin.asia>
 * @copyright  2010 Hidehito NOZAWA
 * @license    http://www.gnu.org/licenses/gpl-2.0.html GNU GPL v2
 *
 */

class Paylog_Controller_DeleteBook extends Paylog_Abstract_Controller
{
	protected $bookHand = null;
	protected $bookObj  = null;
	protected $relBookUserHand = null;
	protected $bookId   = null;

	protected $errors   = array();

	public function __construct()
	{
		parent::__construct();
		$this->bookHand = new Paylog_Object_BookHandler;
		$this->relBookUserHand = new Paylog_Object_RelBookUserHandler;
		$this->bookId   = Paylog::get('id');

		$this->bookObj = $this->bookHand->load($this->bookId);

		$this->output['errors'] =& $this->errors;
	}

	public function main()
	{
		$this->_validateAccess();

		try
		{
			if ( Paylog::post('delete') )
			{
				$this->_delete();
			}
		}
		catch(Exception $e)
		{
		}
		
		$this->_default();
	}

	protected function _validateAccess()
	{
		if ( !Paylog::$cms->isUser() )
		{
			Paylog::redirect("Please Login");
		}

		if ( !$this->bookId )
		{
			Paylog::redirect("Book is not selected.");
		}

		if ( !$this->bookHand->isBookExists($this->bookId) )
		{
			Paylog::redirect("Book deos not exists.");
		}

		if ( !$this->relBookUserHand->isOwner(Paylog::$cms->userId) )
		{
			Paylog::redirect("Only owner can edit.");
		}
	}

	protected function _default()
	{
		$this->output['token']  = Paylog_Class_Ticket::issue();

		$this->output['book'] = array(
			'id'   => $this->bookObj->getVar('id'),
			'name' => $this->bookObj->getVar('name'),
		);

		$this->_view();
	}

	protected function _delete()
	{
		$this->_validateInput();

		if ( !$this->bookHand->delete($this->bookId) )
		{
			$this->_addError("Book deleting failed.");
			$this->_riseError();
		}

		if ( !$this->relBookUserHand->deleteByBookId($this->bookId) )
		{
		}

		$balanceHand = new Paylog_Object_BalanceHandler;

		if ( !$balanceHand->deleteByBookId($this->bookId) )
		{
		}

		Paylog::redirect("Book successly deleted.");
	}

	protected function _validateInput()
	{
		$token = Paylog::post('token');
		if ( !Paylog_Class_Ticket::check($token) )
		{
			$this->_addError("Ticket Error");
		}

		if ( count($this->errors) > 0 )
		{
			$this->_riseError();
		}
	}

	protected function _addError($msg)
	{
		$this->errors[] = Paylog::msg($msg);
	}

	protected function _riseError()
	{
		throw new Exception();
	}
}

?>
